package com.k.kpp.util.rpc.netty.udp.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author kivil
 */
public class UdpClientHandlerOne extends SimpleChannelInboundHandler<DatagramPacket> {
    private String requestId;
    private volatile String responseData;

    public UdpClientHandlerOne(String requestId) {
        this.requestId = requestId;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket packet) throws Exception {
        String receiveXml = packet.content().toString(StandardCharsets.UTF_8);
        responseData = receiveXml;
        System.out.println("udp client receive0：" + Thread.currentThread() + " client channelRead0:" + receiveXml);
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public String getResponseDataWait(long timeout, TimeUnit unit) {
        long curMillis = System.currentTimeMillis();
        long timeoutMillis = unit.toMillis(timeout);
        boolean responseDataOk = false;
        while (!responseDataOk) {
            if (responseData != null) {
                responseDataOk = true;
            }
            long durMillis = System.currentTimeMillis();
            if ((durMillis - curMillis) > timeoutMillis) {
                throw new RuntimeException(String.format("请求超时:requestId:%s, timeout:%sms,", requestId, timeoutMillis));
            }
        }
        return responseData;
    }
}
